package com.example.shgt.fragment;
import com.example.shgt.DetailsActivity;
import com.example.shgt.entity.GoodsData;
import static android.content.Context.MODE_PRIVATE;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.shgt.R;
//import com.example.shgt.adapter.LeftListAdapter;
import com.example.shgt.adapter.RightListAdapter;
import com.example.shgt.adapter.RightListAdapter;
import com.example.shgt.entity.Data;
import com.example.shgt.entity.ProductInfo;
import com.example.shgt.entity.Record;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeFragment extends Fragment {

    private View rootView;
    private final Gson gson = new Gson();
    private RecyclerView leftRecyclerView;
    private RecyclerView rightRecyclerView;
//    private LeftListAdapter mLeftListAdapter;
    private RightListAdapter mRightListAdapter;
    private List<Record> recordList;
    private List<String> leftDataList = new ArrayList<>();
    private SharedPreferences mSharedPreferences;
    private GoodsData goodsData; // 假设 GoodsData 是您获取的商品数据模型
    private ImageView goodsImage; // 显示商品图片的 ImageView


    private Handler uiHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 200) {
                ProductInfo dataResponseBody = (ProductInfo) msg.obj;
                if (dataResponseBody != null && dataResponseBody.getData() != null) {
                    mRightListAdapter.setListData(dataResponseBody.getData().getRecords());
                } else {
                    Toast.makeText(getContext(), "数据加载失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        //设置页面布局格式:瀑布流布局
//        leftRecyclerView = rootView.findViewById(R.id.leftRecyclerView);
        rightRecyclerView = rootView.findViewById(R.id.rightRecyclerView);
        StaggeredGridLayoutManager sglm = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        rightRecyclerView.setLayoutManager(sglm);


//        mLeftListAdapter = new LeftListAdapter(leftDataList);
//        leftRecyclerView.setAdapter(mLeftListAdapter);

        recordList = new ArrayList<>();
        mRightListAdapter = new RightListAdapter(recordList);
        rightRecyclerView.setAdapter(mRightListAdapter);

        // 添加类目按钮
        ImageButton categoryButton = rootView.findViewById(R.id.categoryButton);
        categoryButton.setOnClickListener(v -> showPopupMenu(v));

            initLeftDataList();

        mSharedPreferences = requireActivity().getSharedPreferences("UserPrefs", MODE_PRIVATE);
        String userIdString = mSharedPreferences.getString("userId", null);
        long userId = userIdString != null ? Long.parseLong(userIdString) : 0;

        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString("id", String.valueOf(userId)); // 确保在适当的位置写入userId
        editor.apply();
        Log.d("SharedPreferences", "User ID saved: " + userId);

        getHttpData(userId);//默认加载所有商品

        mSharedPreferences = requireActivity().getSharedPreferences("ProductPrefs", MODE_PRIVATE);
        long ProductId = mSharedPreferences.getLong("id", 2);


        editor.putString("id", String.valueOf(ProductId)); // 确保在适当的位置写入userId
        editor.apply();
        Log.d("SharedPreferences", "Product ID saved: " + ProductId);



        // 设置点击监听器
        mRightListAdapter.setRightListOnItemClickListener(productId -> {
            Intent intent = new Intent(getActivity(), DetailsActivity.class);
            intent.putExtra("id", productId); // 传递产品 ID
            startActivity(intent);
        });

//        mLeftListAdapter.setmLeftListOnClickItemLitener(position -> {
//            mLeftListAdapter.setCurrentIndex(position);
//        });

        return rootView;
    }

    // 显示 PopupMenu
    private void showPopupMenu(View view) {
        PopupMenu popupMenu = new PopupMenu(getContext(), view, Gravity.NO_GRAVITY, 0, R.style.CustomPopupMenu);
        popupMenu.getMenuInflater().inflate(R.menu.popupmenu, popupMenu.getMenu());
        mSharedPreferences = requireActivity().getSharedPreferences("UserPrefs", MODE_PRIVATE);
        String userIdString = mSharedPreferences.getString("userId", null);
        long userId = userIdString != null ? Long.parseLong(userIdString) : 0;

        // 设置菜单项点击事件
        popupMenu.setOnMenuItemClickListener(item -> {
            long productId = -1; // 默认类型

            if (item.getItemId() == R.id.category_phone) {
                productId = 1;
            } else if (item.getItemId() == R.id.category_luxury) {
                productId = 2;
            } else if (item.getItemId() == R.id.category_trendy) {
                productId = 3;
            } else if (item.getItemId() == R.id.category_beauty) {
                productId = 4;
            } else if (item.getItemId() == R.id.category_digital) {
                productId = 5;
            } else if (item.getItemId() == R.id.category_trendy_toys) {
                productId = 6;
            } else if (item.getItemId() == R.id.category_games) {
                productId = 7;
            } else if (item.getItemId() == R.id.category_books) {
                productId = 8;
            } else if (item.getItemId() == R.id.category_food) {
                productId = 9;
            } else if (item.getItemId() == R.id.category_antiques) {
                productId = 10;
            } else if (item.getItemId() == R.id.category_maternity) {
                productId = 11;
            } else if (item.getItemId() == R.id.category_home) {
                productId = 12;
            } else if (item.getItemId() == R.id.category_instruments) {
                productId = 13;
            } else if (item.getItemId() == R.id.category_others) {
                productId = 14;
            }else if (item.getItemId() == R.id.first)
                getHttpData(userId);//默认加载所有商品


            // 处理分类选择
            fetchProductsByTypeId(userId,productId);
            return true;
        });

        popupMenu.show();
    }

    // 模拟根据分类 ID 获取产品
    private void fetchProductsByTypeId(Long userId,long productId) {
        // 更新请求 URL，包含 productId 查询参数
        String url = "https://api-store.openguet.cn/api/member/tran/goods/all?userId="
                + userId
                + "&typeId=" + productId
                + "&size=" + 10000; // 根据分类筛选

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("appId", "479dbe79299a4653ada0432942111871")
                .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("API Failure", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Type jsonType = new TypeToken<ProductInfo>() {}.getType();
                    String body = response.body().string();
                    Log.d("info", body);
                    ProductInfo dataResponseBody = gson.fromJson(body, jsonType);

                    if (dataResponseBody.getCode() == 200) {
                        getActivity().runOnUiThread(() -> {
                            Data dataInfo = dataResponseBody.getData();
                            if (dataInfo != null && dataInfo.getRecords() != null) {
                                mRightListAdapter.setListData(dataInfo.getRecords()); // 显示请求到的商品信息
                            } else {
                                Toast.makeText(getContext(), "没有找到相应的商品", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } else {
                    Log.e("API Error", "Request failed: " + response.code());
                }
            }
        });
    }


    private void initLeftDataList() {
        leftDataList.add("全部");
//
    }

    private void getHttpData(long userId) {
        String url = "https://api-store.openguet.cn/api/member/tran/goods/all?userId=" + userId + "&size=" + 10000;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("appId", "479dbe79299a4653ada0432942111871")
                .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("API Failure", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Type jsonType = new TypeToken<ProductInfo>() {}.getType();
                    String body = response.body().string();
                    Log.d("info", body);
                    ProductInfo dataResponseBody = gson.fromJson(body, jsonType);
                    Log.d("info", dataResponseBody.toString());

                    if (dataResponseBody.getCode() == 200) {
                        getActivity().runOnUiThread(() -> {

                            Data dataInfo = dataResponseBody.getData();
                            if (dataInfo != null && dataInfo.getRecords() != null) {

                                mRightListAdapter.setListData(dataInfo.getRecords()); // 保存所有商品信息

                                saveRecordData(dataInfo.getRecords());
                            } else {
                                Toast.makeText(getContext(), "数据加载失败", Toast.LENGTH_SHORT).show();
                            }

                        });
                    }
                } else {
                    Log.e("API Error", "Request failed: " + response.code());
                }
            }

            private void saveRecordData(List<Record> records) {
                SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("ProductPrefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                // 将记录保存到 SharedPreferences
                for (Record record : records) {
                    editor.putString(String.valueOf(record.getId()), new Gson().toJson(record));
                }
                editor.apply(); // 提交更改

            }
        });
    }
}
